package com.aabte.springcloudlearn.ribbonhystrixcustomerdemo.hystrix;

import com.aabte.springcloudlearn.common.beans.User;
import com.aabte.springcloudlearn.ribbonhystrixcustomerdemo.service.UserCustomerService;
import com.google.common.collect.Lists;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixThreadPoolKey;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author Daniel
 */
@Slf4j
public class UserBatchCommand extends HystrixCommand<List<User>> {

    public static final String COMMAND_KEY = "userBatchCommand";

    private UserCustomerService userCustomerService;
    private List<Long> ids;

    public UserBatchCommand(UserCustomerService userCustomerService, List<Long> ids) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(COMMAND_KEY)));
        this.userCustomerService = userCustomerService;
        this.ids = ids;
    }

    public UserBatchCommand(HystrixCommandGroupKey group, UserCustomerService userCustomerService, List<Long> ids) {
        super(group);
        this.userCustomerService = userCustomerService;
        this.ids = ids;
    }

    public UserBatchCommand(HystrixCommandGroupKey group, HystrixThreadPoolKey threadPool, UserCustomerService userCustomerService, List<Long> ids) {
        super(group, threadPool);
        this.userCustomerService = userCustomerService;
        this.ids = ids;
    }

    public UserBatchCommand(HystrixCommandGroupKey group, int executionIsolationThreadTimeoutInMilliseconds, UserCustomerService userCustomerService, List<Long> ids) {
        super(group, executionIsolationThreadTimeoutInMilliseconds);
        this.userCustomerService = userCustomerService;
        this.ids = ids;
    }

    public UserBatchCommand(HystrixCommandGroupKey group, HystrixThreadPoolKey threadPool, int executionIsolationThreadTimeoutInMilliseconds, UserCustomerService userCustomerService, List<Long> ids) {
        super(group, threadPool, executionIsolationThreadTimeoutInMilliseconds);
        this.userCustomerService = userCustomerService;
        this.ids = ids;
    }

    public UserBatchCommand(Setter setter, UserCustomerService userCustomerService, List<Long> ids) {
        super(setter);
        this.userCustomerService = userCustomerService;
        this.ids = ids;
    }

    @Override
    protected List<User> run() throws Exception {
        log.info("Start UserBatchCommand.run. ids: {}", ids);
        List<User> users = userCustomerService.findAll(ids);
        log.info("End UserBatchCommand.run. users: {}", users);
        return users;
    }

    @Override
    protected List<User> getFallback() {
        log.warn("Invoke userBatchCommand failed. ids: {}", ids);
        return Lists.newArrayList();
    }
}
